package com.lagou.zkweb;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.io.StringReader;
import java.util.Properties;

public class Watcher {

    private static ZkClient zkClient = new ZkClient(CommonUtil.ZK_SERVER);


    public static void subDataChanges() {
        zkClient.subscribeDataChanges(CommonUtil.DB_PATH, new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
                System.out.println("数据库配置发生变更");
                Object dbConfig = zkClient.readData(CommonUtil.DB_PATH);

                CommonUtil.dbProperties = new Properties();
                CommonUtil.dbProperties.load(new StringReader((String) dbConfig));
                // 释放连接池
                DruidManager.close();

                // 创建新的连接池
                DruidManager.createConnectPool();

                System.out.println("创建新的连接池后重新获取数据");
                Select.selectData();
                CommonUtil.countDownLatch.countDown();
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("数据库配置被删除");
            }
        });
    }
}
